<template>
  <div class="globalHeader">
    <a-row :wrap="false">
      <a-col flex="auto">
        <a-menu
          mode="horizontal"
          :selected-keys="selectedKeys"
          @menu-item-click="doMenuClick"
        >
          <a-menu-item
            key="0"
            :style="{ padding: 0, marginRight: '38px' }"
            disabled
          >
            <div class="title-bar">
              <img class="logo" src="@/assets/logo.png" />
              <div class="title">用户中心</div>
            </div>
          </a-menu-item>
          <a-menu-item v-for="item in routes" :key="item.path">
            {{ item.name }}
          </a-menu-item>
        </a-menu>
      </a-col>
      <a-col flex="100px">
        <div class="user-login-status">
          <div v-if="loginUserStore.loginUser.id">
            <a-dropdown>
              <a-button
                >{{ loginUserStore.loginUser.username ?? "无名" }}
              </a-button>
              <template #content>
                <a-doption @click="handleLogout">退出登录</a-doption>
              </template>
            </a-dropdown>
          </div>
          <div v-else>
            <a-button type="primary" @click="goToLogin">去登录</a-button>
          </div>
        </div>
      </a-col>
    </a-row>
  </div>
</template>
<script setup>
import { useRouter } from "vue-router";
import { routes } from "@/router/routes";
import { ref } from "vue";
import { useLoginUserStore } from "@/store/useLoginUserStore";
import { userLogout } from "@/api/user";
import message from "@arco-design/web-vue/es/message";

const loginUserStore = useLoginUserStore();
const selectedKeys = ref(["/"]);
const router = useRouter();

//注销用户
const handleLogout = async () => {
  const res = await userLogout();
  if (res.data.code === 0) {
    message.success("退出成功");
    loginUserStore.setLoginUser("");
    router.replace({
      path: "/user/login",
    });
  } else {
    message.error("发生异常，退出失败");
  }
};

// 跳转到登陆页面
const goToLogin = () => {
  router.push({ path: "/user/login" });
};

//路由跳转
const doMenuClick = (key) => {
  router.push({
    path: key,
  });
};
//监听路由变化，更新当前菜单选中状态
router.afterEach((to, from, failure) => {
  selectedKeys.value = [to.path];
});
</script>
<style scoped>
.title-bar {
  display: flex;
  align-items: center;
}

.logo {
  height: 45px;
}

.title {
  color: #444;
  margin-left: 16px;
}

.user-login-status {
  padding-top: 20px;
}
</style>
<script setup lang="ts"></script>
